package com.yocard.yxyd.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yocard.yxyd.R;
import com.yocard.yxyd.adapter.CsmListAdapter;
import com.yocard.yxyd.base.Constants;
import com.yocard.yxyd.http.model.request.CsmListRequest;
import com.yocard.yxyd.http.model.response.CommonBean;
import com.yocard.yxyd.http.model.response.CsmOrderListBean;
import com.yocard.yxyd.others.ClassicsHeader;
import com.yocard.yxyd.ui.activity.CsmDetailActivity;
import com.yocard.yxyd.ui.contract.CustomerContract;
import com.yocard.yxyd.ui.fragment.base.BaseBackFragment;
import com.yocard.yxyd.ui.presenter.CustomerPresenter;
import com.yocard.yxyd.ui.view.CsmDrawerView;
import com.yocard.yxyd.utils.CommonUtils;
import com.yocard.yxyd.utils.util.ActivityUtils;
import com.yocard.yxyd.utils.util.KeyboardUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.yocard.yxyd.event.EventCode.REFRESH_RECEIVED_ORDER_lIST;

/**
 * Created on 2019/4/8.
 */
public class CustomerFragment extends BaseBackFragment<CustomerPresenter> implements CustomerContract.View {

    @BindView(R.id.empty_view)
    View emptyView;
    @BindView(R.id.recycle_view)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.drawer)
    CsmDrawerView drawerView;
    @BindView(R.id.rl_head_layout)
    RelativeLayout rlHeadLayout;
    @BindView(R.id.refresh_header)
    ClassicsHeader classicsHeader;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_switch)
    TextView tvSwitch;

    private int currentPage = 1;
    private List<CsmOrderListBean.OrderList> datas = new ArrayList<>();
    CsmListRequest request;
    protected CsmListAdapter mAdapter;

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ft_customer;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPresenter.setUpelasHead(rlHeadLayout, classicsHeader);//弹性刷新拉伸
    }
    @Override
    public void onResume() {
        super.onResume();

        ImmersionBar.with(this).statusBarColor(R.color.transparent)
                .statusBarDarkFont(true).init();
    }

    @Override
    protected void initEventAndData() {
        mAdapter = new CsmListAdapter(datas);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(mAdapter);

        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.shape_transparent));
        recyclerView.addItemDecoration(dividerItemDecoration);
        refreshLayout.setOnRefreshListener(refreshLayout1 -> {
            currentPage = 1;
            request.setPage(currentPage);
            mPresenter.fetchCsmList(currentPage, request);
        });

        refreshLayout.setOnLoadMoreListener(refreshLayout1 -> {
            currentPage++;
            request.setPage(currentPage);
            mPresenter.fetchCsmList(currentPage, request);
        });


        showLoadingDialog();
        request = new CsmListRequest(currentPage);
        mPresenter.fetchCsmList(currentPage, request);

        initDrawer();
        drawerView.setSelectListener(value -> {
            if(value == null) {
                request = new CsmListRequest();
                return;
            }
            setIcoSelect(!CommonUtils.checkObjAllFieldsIsNull(value));
            recyclerView.scrollToPosition(0);
            drawerLayout.closeDrawer(drawerView);
            request = value;
            currentPage = 1;
            request.setPage(currentPage);
            showLoadingDialog();
            mPresenter.fetchCsmList(currentPage, request);
        });
        mAdapter.setOnItemClickListener(value -> {
            Bundle bundle = new Bundle();
            bundle.putString("id", value.getId());
            ActivityUtils.startActivity(bundle, CsmDetailActivity.class);
        });
    }


    private void initDrawer() {
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(@NonNull View view, float v) {
                KeyboardUtils.hideSoftInput(getActivity());

            }

            @Override
            public void onDrawerOpened(@NonNull View view) {

            }

            @Override
            public void onDrawerClosed(@NonNull View view) {
            }

            @Override
            public void onDrawerStateChanged(int i) {

            }
        });
    }

    @OnClick({R.id.tv_switch})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_switch:
                drawerLayout.openDrawer(drawerView);
                break;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden && drawerLayout.isDrawerOpen(drawerView)) {
            drawerLayout.closeDrawer(drawerView);
            drawerView.resetValues();
        }
    }

    @Override
    public boolean onBackPressed() {
        if(drawerLayout.isDrawerOpen(drawerView)) {
            drawerLayout.closeDrawer(drawerView);
            return true;
        }
        return false;
    }

    @Override
    public void onFetcheList(List<CsmOrderListBean.OrderList> list) {
        if (currentPage == 1) {
            datas.clear();
            if (list.size() == 0) {
                if (getIcoSelectStatus()) {
                    tvTip.setText(getString(R.string.no_result));
                } else {
                    tvTip.setText(getString(R.string.empty_customer_list));
                }
                showEmptyView(emptyView);
            } else {
                hiddenEmptyView(emptyView);
                datas.addAll(list);
            }
            refreshLayout.finishRefresh();
            refreshLayout.resetNoMoreData();
            mAdapter.notifyDataSetChanged();
            dismisDialog();
        } else {
            datas.addAll(list);
            refreshLayout.finishLoadMore();
            if (list.size() < Constants.PAGE_SIZE) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showErrorMsg(String msg) {
        super.showErrorMsg(msg);
        dismisDialog();
        //清楚列表数据
        datas.clear();
        mAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if(currentPage == 1){
            showEmptyView(emptyView);
            tvTip.setText(getString(R.string.empty_customer_list));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFreshEvent(CommonBean bean) {
        if (bean.getCode() == Constants.CODE_REFRESH || bean.getCode() == REFRESH_RECEIVED_ORDER_lIST) {
            currentPage = 1;
            request = new CsmListRequest(currentPage);
            mPresenter.fetchCsmList(currentPage, request);
            recyclerView.scrollToPosition(0);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void setIcoSelect(boolean select) {
        tvSwitch.setSelected(select);
    }

    public boolean getIcoSelectStatus() {
        return tvSwitch.isSelected();
    }

    public void smoothScrollToTop(){
        recyclerView.smoothScrollToPosition(0);
    }
}
